import React, {useEffect, useMemo, useState} from 'react'
import {
	Space,
	Button,
	Modal,
	Form,
	Radio,
	Input,
	message,
	Tag,
	Popconfirm,
} from 'antd'
import {history, connect, useDispatch} from 'umi'
import {
	PlusOutlined,
	ArrowUpOutlined,
	ArrowDownOutlined,
} from '@ant-design/icons'
import moment from 'moment'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import {getDict} from '@/service/common/dict'
import {
	DriverRewardRulesColumns,
	PageType,
	activeStatus,
	activeStatusSearch,
	disableStatusList,
	auditStatus,
	subsidyType,
	activitiesType,
	errorColumns,
	isRecover,
	Relevance,
} from '../constant'
import styles from './index.less'
import {getAllCitys, getCompany} from '@/service/common/index'
import {
	getTableList,
	processAudit,
	getExportErrorData,
	importReward,
	importCheckReward,
	updateStatus,
	getInitFormDetailShop,
} from '@/service/carRewardRule/rewardRule'
import {translateDataToTree} from '@/utils/common/index'
import BatchUpload from '@/components/BatchUpload'
import {modalApi} from '@/utils/modalReq'
import {downloadDocumentUrl} from '@/service/common/download'
import Permissions from '@/components/Permissions'

interface CityOption {
	value: string | number
	label: string
	children?: CityOption[]
}
function List(props: {
	user: {orgId: any; userId: any}
	driverRewardRules: any
}) {
	const dispatch = useDispatch()
	const [pagination, setPagination] = useState({
		current: 1,
		size: 10,
	})
	const [total, setTotal] = useState(0)
	const [totalSum, sumTotalSum] = useState(0)
	const [loading, setLoading] = useState(false)
	const [visible, setVisible] = useState(false)
	const [isScheme, setIsScheme] = useState<boolean>(false)
	const [pageParams, setPageParams] = useState({
		current: 1,
		size: 10,
	})
	const [selectText, setSelectText] = useState<any>()
	const [form] = Form.useForm()
	const [dataList, setDataList] = useState([])
	const [selectRows, setSelectRows] = useState<any[]>([])
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	const [relevanceData, setRelevanceData] = useState<any[]>([]) // 表单参数
	const [searchData, setSearchData] = useState({})
	const [companyData, setCompanyData] = useState<any[]>([]) // 初始化所属公司
	const [citysList, setCitysList] = useState<CityOption[]>([]) // 初始化城市
	const [dict, setDict] = useState({
		entity_type: [],
		issue_kind: [],
	})
	const {
		driverRewardRules,
		user: {orgId, userId},
	} = props
	const formItems = useMemo(
		() => [
			{
				type: 'group',
				key: 'group',
				groupItems: [
					{
						type: 'select',
						label: '主体名称',
						name: 'subjectId',
						key: 'subjectId',
						keys: 'id',
						title: 'name',
						items: driverRewardRules?.MainCompany,
						placeholder: '请输入',
					},
					{
						type: 'cascader',
						label: '城市名称',
						name: 'cityId',
						key: 'cityId',
						fieldNames: {
							label: 'name',
							value: 'id',
							children: 'cityInfoList',
						},
						keys: 'id',
						items: [...citysList],
						placeholder: '请输入',
					},
					{
						type: 'treeSelect',
						label: '所属公司',
						name: 'orgId',
						key: 'orgId',
						title: 'name',
						keys: 'id',
						treeData: [...companyData],
						placeholder: '请选择',
					},
				],
			},
			{
				type: 'group',
				key: 'group2',
				groupItems: [
					{
						type: 'select',
						label: ' 活动状态',
						name: 'activeStatus',
						key: 'activeStatus',
						title: 'label',
						keys: 'value',
						items: [...activeStatusSearch],
					},
					{
						type: 'input',
						label: '司机奖励ID',
						name: 'rewardId',
						key: 'rewardId',
						placeholder: '请输入',
					},
					{
						type: 'select',
						label: ' 审核状态',
						name: 'auditStatus',
						key: 'auditStatus',
						title: 'label',
						keys: 'value',
						items: [...auditStatus],
						placeholder: '请输入',
					},
				],
			},
			{
				type: 'group',
				key: 'group3',
				groupItems: [
					{
						type: 'dateRange',
						label: ' 开始时间',
						name: 'startStartTime',
						key: 'startStartTime',
						placeholder: '请输入',
					},
					{
						type: 'dateRange',
						label: ' 结束时间',
						name: 'endStartTime',
						key: 'endStartTime',
						placeholder: '请输入',
					},
					{
						type: 'select',
						label: '补贴订单类型',
						name: 'subsidyType',
						key: 'subsidyType',
						title: 'label',
						keys: 'value',
						items: [...subsidyType],
						placeholder: '请输入',
					},
				],
			},
			{
				type: 'group',
				key: 'group4',
				groupItems: [
					{
						type: 'select',
						label: ' 补贴订单方式',
						name: 'activitiesType',
						key: 'activitiesType',
						title: 'label',
						keys: 'value',
						items: [...activitiesType],
						placeholder: '请输入',
					},
					{},
					{},
				],
			},
		],
		[citysList, driverRewardRules?.MainCompany, companyData],
	)

	/** 获取所属公司数据 */
	const onCompany = () => {
		getCompany({merchantId: orgId}).then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res?.data)
				setCompanyData([...list])
			}
		})
	}
	/** 获取城市数据 */
	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.success) {
				setCitysList(() => res.data)
			}
		})
	}

	const openAudit = () => {
		if (selectRows.length === 0) {
			message.error('请选择奖励规则')
		} else {
			setVisible(true)
		}
	}

	useEffect(() => {
		getCitysFun()
		onCompany()
		dispatch({
			type: 'driverRewardRules/getMainCompanyList',
		})
	}, [orgId, pagination])

	// 获取报表数据
	const onListFun = () => {
		setLoading(true)
		getTableList({
			...pagination,
			...searchData,
		})
			.then((res: any) => {
				if (res?.success) {
					setDataList(() => res?.data?.records)
					setTotal(res?.data?.total)
				}
				setLoading(false)
			})
			.catch(() => {
				setLoading(false)
			})
	}
	/**
	 * 批量审核数据
	 */
	const onAuditSave = async () => {
		const data = await form.validateFields()
		const id = selectRows.map((item) => item.id)
		const params = {
			ids: [...id],
			...data,
		}
		processAudit(params)
			.then((res) => {
				if (res?.success) {
					message.success(res?.msg)
					form.resetFields()
					setVisible(false)
					onListFun()
				}
			})
			.catch(() => {})
	}
	useEffect(() => {
		getDict(
			{
				dictKeys: ['entity_type', 'issue_kind'],
			},
			(res: any) => {
				setDict(() => res)
			},
		)
	}, [])
	useEffect(() => {
		onListFun()
	}, [pagination, searchData, dict])

	// 打开关联的商品方案 同时获取关联的商品方案数据
	const openModel = (text: any) => {
		setIsScheme(true)
		setSelectText(() => text)
		setPageParams({
			current: 1,
			size: 10,
		})
	}

	const getList = () => {
		const params = {
			...pageParams,
			rewardId: selectText.rewardId,
		}
		getInitFormDetailShop(params)
			.then((res) => {
				if (res?.success) {
					setRelevanceData(() => res?.data?.records)
					sumTotalSum(res?.data?.total)
				}
			})
			.catch(() => {})
	}

	useEffect(() => {
		if (isScheme) getList()
	}, [pageParams])

	const isUpdateStatus = (record: Record<string, any>) => {
		const params = {
			id: record?.id,
			activeStatus: record?.activeStatus === 1 ? 2 : 1,
		}
		updateStatus(params)
			.then((res) => {
				if (res?.success) {
					setPagination(pagination)
					onListFun()
				}
			})
			.catch(() => {})
	}
	const Colunms: any[] = [
		{
			title: '司机奖励ID',
			dataIndex: 'rewardId',
			align: 'center',
			ellipsis: true,
			width: 240,
		},
		{
			title: '奖励名称',
			dataIndex: 'rewardName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: string) => text || '--',
		},
		{
			title: '补贴方式',
			dataIndex: 'activitiesType',
			align: 'center',
			width: 100,
			render: (text: number) => (
				<>
					{activitiesType?.map((item: any) => {
						if (item?.value === text) {
							return <Tag color="processing">{item?.label}</Tag>
						}
						return ''
					})}
				</>
			),
		},
		{
			title: '补贴订单类型',
			dataIndex: 'subsidyTypename',
			align: 'center',
			width: 200,
			ellipsis: true,
			render: (text: string) => (
				<Tag color="processing"> {text || '--'} </Tag>
			),
		},
		{
			title: '渠道类型',
			dataIndex: 'channelTypename',
			align: 'center',
			width: 200,
			ellipsis: true,
			render: (text: string) => (
				<Tag color="processing"> {text || '--'} </Tag>
			),
		},
		{
			title: '审核状态',
			dataIndex: 'auditStatus',
			align: 'center',
			width: 100,
			render: (text: number) => (
				<>
					{auditStatus?.map((item: any) => {
						if (item?.value === text) {
							return <Tag color="processing">{item?.label}</Tag>
						}
						return ''
					})}
				</>
			),
		},
		{
			title: '活动状态',
			dataIndex: 'activeStatus',
			align: 'center',
			width: 150,
			render: (text: number) => (
				<>
					{activeStatus?.map((item: any) => {
						if (item?.value === text) {
							return <Tag color="processing">{item?.label}</Tag>
						}
						return ''
					})}
				</>
			),
		},
		{
			title: '是否与商品方案合并审核',
			dataIndex: 'isConsolidatedAudit',
			align: 'center',
			width: 250,
			render: (text: number) => (
				<>
					{isRecover?.map((item: any) => {
						if (item?.value === text) {
							return <Tag color="processing">{item?.label}</Tag>
						}
						return ''
					})}
				</>
			),
		},
		{
			title: '关联商品方案',
			dataIndex: '',
			align: 'center',
			width: 150,
			render: (_: any, text: any) => (
				<>
					<Button type="link" onClick={() => openModel(text)}>
						查看
					</Button>
				</>
			),
		},
		{
			title: '实物类型',
			dataIndex: 'entityType',
			align: 'center',
			width: 150,
			render: (text: any) => {
				const obj: any = dict?.entity_type?.filter(
					(item: {dictKey: any; dictValue: any}) =>
						Number(item.dictKey) === Number(text),
				)
				return obj[0] ? (
					<Tag color="processing">{obj[0].dictValue}</Tag>
				) : (
					'--'
				)
			},
		},
		{
			title: '实物名称',
			dataIndex: 'issueKind',
			align: 'center',
			width: 150,
			render: (text: any) => {
				const obj: any = dict?.issue_kind?.filter(
					(item: {dictKey: any; dictValue: any}) =>
						Number(item.dictKey) === Number(text),
				)
				return obj[0] ? (
					<Tag color="processing">{obj[0].dictValue}</Tag>
				) : (
					'--'
				)
			},
		},
		...DriverRewardRulesColumns,
		{
			title: '天数',
			dataIndex: 'dayNum',
			align: 'center',
			width: 100,
			ellipsis: true,
			render: (text: string) => text || '--',
		},
		{
			title: '金额',
			dataIndex: 'amount',
			align: 'center',
			width: 100,
			ellipsis: true,
			render: (text: number) => (text === -1 ? 0 : text),
		},
		{
			title: '操作',
			width: 300,
			align: 'center',
			fixed: 'right',
			render: (ffield: string, record: Record<string, any>) => {
				const i = disableStatusList.filter(
					(item: any) => item.value === Number(record?.activeStatus),
				)[0]
				return (
					<div>
						<Permissions permissionID="amc_merchantCenter_driverRewardRules_view">
							<Button
								type="link"
								onClick={() => {
									history.push({
										pathname:
											'/merchantCenter/driverRewardRules/detail',
										search: `pageType=detail&id=${record.id}&rewardId=${record.rewardId}&orgId=${record.orgId}&processId=${record.processId}`,
										state: record,
									})
								}}>
								查看
							</Button>
						</Permissions>
						{record.isConsolidatedAudit !== 1 &&
						Number(record.createUserId) === Number(userId) &&
						(record.auditStatus === 1 ||
							record.auditStatus === 4) ? (
							<Permissions permissionID="amc_merchantCenter_driverRewardRules_edit">
								<Button
									type="link"
									onClick={() => {
										history.push({
											pathname:
												'/merchantCenter/driverRewardRules/edit',
											search: `pageType=edit&id=${record.id}&rewardId=${record.rewardId}`,
											state: record,
										})
									}}>
									编辑
								</Button>
							</Permissions>
						) : null}
						{record.auditBut === 1 ? (
							<Permissions permissionID="amc_merchantCenter_driverRewardRules_process">
								<Button
									type="link"
									onClick={() => {
										history.push({
											pathname:
												'/merchantCenter/driverRewardRules/process',
											search: `pageType=process&id=${record.id}&rewardId=${record.rewardId}&processId=${record.processId}`,
											state: record,
										})
									}}>
									审核
								</Button>
							</Permissions>
						) : null}
						{record?.activeStatus !== 0 &&
						record?.auditStatus === 3 ? (
							<Permissions permissionID="amc_merchantCenter_driverRewardRules_enable">
								<Popconfirm
									placement="topLeft"
									title="你确定要改变这条数据状态？"
									onConfirm={() => isUpdateStatus(record)}
									okText="确定"
									cancelText="取消">
									<Button type="link" size="small">
										{i?.label}
									</Button>
								</Popconfirm>
							</Permissions>
						) : null}
					</div>
				)
			},
		},
	]
	const ColunmsRelevance: any[] = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text: any, record: any, index: any) {
				return <span>{(pageParams.current - 1) * 10 + index + 1}</span>
			},
		},
		...Relevance,
		{
			title: '首付款',
			dataIndex: 'advancePaymentAmount',
			align: 'center',
			width: 150,
			render: (text: string) => (Number(text) >= 0 ? text : '--'),
		},
		{
			title: '尾款',
			dataIndex: 'balancePaymentAmount',
			align: 'center',
			width: 150,
			render: (text: string) => (Number(text) >= 0 ? text : '--'),
		},
		{
			title: '详情',
			dataIndex: 'status',
			align: 'center',
			width: 100,
			fixed: 'right',
			render: (ffield: string, record: Record<string, any>) => (
				<div>
					<Button
						type="link"
						onClick={() => {
							history.push({
								pathname: '/merchantCenter/commodityPlan/view',
								search: `id=${record.id}`,
								state: record,
							})
							setIsScheme(false)
						}}>
						详情
					</Button>
				</div>
			),
		},
	]
	const onFinish = (values: any) => {
		const paramsSearch = {
			...values,
			cityId: values?.cityId && values?.cityId[1],
			startStartTime:
				values?.startStartTime &&
				moment(values?.startStartTime[0]).format('YYYY-MM-DD'),
			startEndTime:
				values?.startStartTime &&
				moment(values?.startStartTime[1]).format('YYYY-MM-DD'),
			endStartTime:
				values?.endStartTime &&
				moment(values?.endStartTime[0]).format('YYYY-MM-DD'),
			endEndTime:
				values?.endStartTime &&
				moment(values?.endStartTime[1]).format('YYYY-MM-DD'),
		}
		setSearchData({...paramsSearch})
	}

	const onReset = () => {
		const params = {
			current: 1,
			size: 10,
		}
		setPageParams(params)
		setSearchData({})
	}
	const getData = async (): Promise<any> => {
		await onReset()
	}
	return (
		<div className={styles.page}>
			<div className="search">
				<SearchForm
					formLayout={{
						labelCol: {flex: '120px'},
						wrapperCol: {flex: '1'},
					}}
					formItems={formItems}
					onFinish={onFinish}
					onReset={onReset}
				/>
			</div>
			<div className="btnlist">
				<Space size={12}>
					<Permissions permissionID="amc_merchantCenter_driverRewardRules_add">
						<Button
							onClick={() => {
								dispatch({
									type: 'driverRewardRules/updateState',
									payload: {
										outTableList: [],
									},
								})
								history.push({
									pathname:
										'/merchantCenter/driverRewardRules/add',
									query: {
										pageType: PageType.Add,
									},
								})
							}}
							icon={<PlusOutlined />}
							type="primary"
							ghost
							size="small">
							新增
						</Button>
					</Permissions>
					<Permissions permissionID="amc_merchantCenter_driverRewardRules_batch">
						<Button
							onClick={() => openAudit()}
							type="primary"
							disabled={!selectRows?.length}
							size="small">
							批量审核
						</Button>
					</Permissions>
					<Permissions permissionID="amc_merchantCenter_driverRewardRules_import">
						<Button
							icon={<ArrowUpOutlined />}
							size="small"
							onClick={() => setIsUploadModalOpen(true)}>
							导入
						</Button>
					</Permissions>
					<Permissions permissionID="amc_merchantCenter_driverRewardRules_export">
						<Button
							icon={<ArrowDownOutlined />}
							// ghost
							size="small"
							onClick={() => {
								downloadDocumentUrl({
									resourceId: '161',
									queryDesc: '规则列表导出,resourceId:161',
									queryParam: searchData,
								})
							}}>
							导出
						</Button>
					</Permissions>
				</Space>
			</div>
			<div className="table">
				<CustomTable
					pagination
					kid="id"
					params={pagination}
					columns={Colunms}
					loading={loading}
					scroll={{y: 500}}
					total={total}
					callback={(pa: any) => {
						setPagination(pa)
					}}
					showRowSelection
					selectCallback={(keys: string[], rows: any[]) => {
						setSelectRows(rows)
					}}
					getCheckboxProps={{
						getCheckboxProps: (record: any) => {
							if (record?.auditBut !== 1) {
								return {disabled: true}
							}
							return null
						},
					}}
					dataSource={dataList}
				/>
			</div>
			<Modal
				title="批量审核司机奖励规则"
				open={visible}
				onCancel={() => {
					setVisible(false)
				}}
				width={500}
				onOk={onAuditSave}>
				<Form
					layout="horizontal"
					labelCol={{flex: '140px'}}
					labelAlign="right"
					labelWrap
					autoComplete="off"
					name="PersonalInformationFom"
					form={form}>
					<Form.Item
						label="审核状态"
						name="pass"
						rules={[{required: true}]}>
						<Radio.Group>
							<Radio value={1}>审核通过</Radio>
							<Radio value={2}>审核驳回</Radio>
						</Radio.Group>
					</Form.Item>
					<Form.Item label="处理意见" name="message">
						<Input.TextArea
							maxLength={200}
							rows={3}
							placeholder="请输入处理意见,不超过200个字"
						/>
					</Form.Item>
				</Form>
			</Modal>
			<Modal
				title="关联商品方案数据"
				open={isScheme}
				onCancel={() => {
					setIsScheme(false)
				}}
				footer={null}
				width={1400}>
				<CustomTable
					pagination
					key="id"
					params={pageParams}
					columns={ColunmsRelevance}
					total={totalSum}
					scroll={{y: 500}}
					callback={(pa: any) => {
						setPageParams(pa)
					}}
					dataSource={relevanceData}
				/>
			</Modal>
			<BatchUpload
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={importReward}
				onTableList={getExportErrorData}
				getListData={getData}
				type={1} // 检查参数
				saveType={2} // 保存参数
				fileNmae="excel"
				modular="material" // 文件导入需使用2进制文件 请求方式采用formData形式
				downloadUrl={`${modalApi.customer}/shopec-template-config/templateconfig/getDownloadUrl`}
				uploadFileUrl={importCheckReward}
				columns={errorColumns}
				sourceId={46}
				templateType="司机奖励规则"
			/>
		</div>
	)
}

export default connect(({user, driverRewardRules}: any) => ({
	user,
	driverRewardRules,
}))(List)
